package com.riteny.common.schedule.util;

import com.riteny.common.schedule.entity.ScheduleTask;
import com.riteny.common.schedule.exception.ScheduleTaskException;
import com.riteny.common.schedule.exception.ScheduleTaskNotFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Riteny
 * 2020/9/25  14:55
 */
public class ScheduleTaskPool {

    private static Map<String, ScheduleTask> scheduleTasks = new HashMap<>();

    /**
     * 添加一個定時任務
     *
     * @param taskName     任務名稱
     * @param scheduleTask 任務内容
     */
    public static void add(String taskName, ScheduleTask scheduleTask) {
        scheduleTasks.put(taskName, scheduleTask);
    }

    /**
     * 停止並移除任務
     *
     * @param taskName 任務名稱
     */
    public static void remove(String taskName) throws ScheduleTaskException {

        ScheduleTask scheduleTask = get(taskName);

        scheduleTask.getFuture().cancel(true);
        scheduleTasks.remove(taskName);
    }

    /**
     * 停止任務
     *
     * @param taskName 任務名稱
     */
    public static void stop(String taskName) throws ScheduleTaskException {

        ScheduleTask scheduleTask = get(taskName);

        scheduleTask.getFuture().cancel(true);
    }

    /**
     * 根據名稱獲取對應的任務詳情
     *
     * @param taskName 任務名稱
     * @return 任務詳情
     */
    public static ScheduleTask get(String taskName) throws ScheduleTaskException {

        ScheduleTask scheduleTask = scheduleTasks.get(taskName);

        if (scheduleTask == null) {
            throw new ScheduleTaskNotFoundException("Schedule task not found [" + taskName + "]");
        }

        return scheduleTask;
    }

    /**
     * 獲取任務池内所有任務
     *
     * @return 任務列表
     */
    public static Map<String, ScheduleTask> getScheduleTasks() {
        return scheduleTasks;
    }
}
